using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Npgsql;
using Microsoft.EntityFrameworkCore;
using AdminSG3L.Infrastructure.Data;

namespace AdminSG3L.IntegrationTests
{
    public abstract class IntegrationTestBase : IClassFixture<WebApplicationFactory<Program>>
    {
        protected readonly HttpClient _client;
        protected readonly WebApplicationFactory<Program> _factory;

        protected IntegrationTestBase(WebApplicationFactory<Program> factory = null)
        {
            _factory = factory ?? new WebApplicationFactory<Program>()
                .WithWebHostBuilder(builder =>
                {
                    builder.ConfigureAppConfiguration((context, config) =>
                    {
                        config.AddJsonFile("appsettings.Test.json");
                    });
                });

            // Verify and migrate database
            InitializeDatabase();

            _client = _factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });
        }

        private void InitializeDatabase()
        {
            using var scope = _factory.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<AdminDbContext>();
            dbContext.Database.Migrate();
        }

        public virtual async Task InitializeAsync()
        {
            await Task.CompletedTask;
        }
    }
}
